   /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iss.basket.servlet;

import com.iss.basket.bizLogic.AuthenticateService;
import com.iss.basket.models.Users;
import com.iss.basket.util.SearchCookie;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author yc
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet{

    @EJB private AuthenticateService loginService;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
       
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        boolean remember = Boolean.parseBoolean(req.getParameter("remember"));
        try {
            //authenticate
            req.login(username, password);
            //check if remember is true
            //if true invoke loginService.rememberUser
            if(remember)
            {
                String uid = loginService.rememberUser(username);
                //create new cookie with uid, replacing any existing cookies and db entries
                Cookie rememberCookie = new Cookie("remember", uid);
                resp.addCookie(rememberCookie);
            }
            else //else remove user from remembercheck and also remove any cookies
            {
                loginService.forgetUser(username);
                Cookie c = SearchCookie.getCookie(req.getCookies(), "remember");
                if(c!=null)
                {
                    c.setMaxAge(0); //expires immediately
                }
            }   
            
            Cookie c = new Cookie("verified", "true");
            resp.addCookie(c);            
            resp.setStatus(HttpServletResponse.SC_OK);      
            
        } catch (ServletException ex) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        
        if(req.getUserPrincipal()==null)
        {
            
            //check if cookie exists
            Cookie rememberCookie = SearchCookie.getCookie(req.getCookies(),"remember");
            boolean loginResult=false;
            if(rememberCookie!=null)
            {
                //try to perform log-in
                Users user = loginService.rememberVerify(rememberCookie.getValue());
                if(user!=null)
                {
                    try {
                        req.login(user.getUsername(), user.getPassword());
                        loginResult = true;
                        Cookie c = new Cookie("verified", "true");
                        resp.addCookie(c);
                        
                        try {
                            resp.sendRedirect(req.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI).toString().replace("", ""));
                            return;
                        } catch (IOException ex) {
                            System.out.println("Forward Fail");
                        }
                        
                    } catch (ServletException ex) {
                        System.out.println("login fail");                       
                    }
                }
                
            }         
            //not logged in            
            
            Cookie c = new Cookie("verified","false");
            resp.addCookie(c);
            RequestDispatcher rd = req.getRequestDispatcher("/login.html");
            try {
                rd.forward(req, resp);                
                
            } catch (ServletException ex) {
                
            } catch (IOException ex) {
               
            }
        }
        else
        {
            Cookie c = new Cookie("verified","true");
            resp.addCookie(c);            
            //shouldn't need to do anything
            
        }
        
    }
    
    
    
}
